<template>
  <div class="home-container">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-left">
        <div class="logo">
          <img src="/logo.png" alt="家政服务平台" />
          <span>家政服务平台</span>
        </div>
        <el-icon><Menu /></el-icon>
        <el-icon><Refresh @click="fetchServices" /></el-icon>
        <span class="nav-text">服务管理</span>
      </div>
      <div class="header-right">
        <el-button class="client-btn">
          <el-icon><Monitor /></el-icon>
          客户端
        </el-button>
        <el-badge is-dot>
          <el-icon><Bell /></el-icon>
        </el-badge>
        <el-icon><Setting /></el-icon>
        <el-dropdown @command="handleCommand">
          <div class="user-info">
            <el-avatar :size="32">{{ userInitials }}</el-avatar>
            <span>{{ username }}</span>
            <el-icon><CaretBottom /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人信息</el-dropdown-item>
              <el-dropdown-item command="settings">账号设置</el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <span style="color: #f56c6c;">注销</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <div class="main-container">
      <!-- 左侧菜单 -->
      <el-aside width="64px" class="sidebar">
        <router-link to="/admin" custom v-slot="{ navigate, isActive }">
          <div class="menu-item" :class="{ active: isActive }" @click="navigate">
            <el-icon><HomeFilled /></el-icon>
            <span>首页</span>
          </div>
        </router-link>
        <router-link to="/admin/service-management" custom v-slot="{ navigate, isActive }">
          <div class="menu-item" :class="{ active: isActive }" @click="navigate">
            <el-icon><Setting /></el-icon>
            <span>服务管理</span>
          </div>
        </router-link>
        <router-link to="/admin/user-management" custom v-slot="{ navigate, isActive }">
          <div class="menu-item" :class="{ active: isActive }" @click="navigate">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </div>
        </router-link>
        <router-link to="/admin/application-management" custom v-slot="{ navigate, isActive }">
          <div class="menu-item" :class="{ active: isActive }" @click="navigate">
            <el-icon><Promotion /></el-icon>
            <span>审批系统</span>
          </div>
        </router-link>
        <router-link to="/admin/worker-management" custom v-slot="{ navigate, isActive }">
          <div class="menu-item" :class="{ active: isActive }" @click="navigate">
            <el-icon><User /></el-icon>
            <span>家政管理</span>
          </div>
        </router-link>
      </el-aside>

      <!-- 主要内容区域 -->
      <el-main class="main-content">
        <div class="service-management">
          <div class="page-header">
            <h2>家政服务管理</h2>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>添加服务
            </el-button>
          </div>
          <br>
          <!-- 服务搜索筛选 -->
          <div class="search-bar">
            <el-form :inline="true" :model="searchForm">
              <el-form-item label="服务类别">
                <el-select
                    v-model="searchForm.category"
                    placeholder="请选择服务类别"
                    clearable
                    style="width: 200px"
                >
                  <el-option
                      v-for="category in serviceCategories"
                      :key="category"
                      :label="category"
                      :value="category"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchServices">搜索</el-button>
                <el-button @click="resetSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 服务列表 -->
          <el-table
              :data="displayedServices"
              style="width: 100%"
              border
              stripe
              v-loading="tableLoading"
          >
            <el-table-column prop="id" label="ID" width="80" align="center" />
            <el-table-column prop="category" label="服务类别" min-width="180" align="center" />
            <el-table-column label="标准价格(元)" min-width="180" align="center">
              <template #default="{ row }">
                <span class="price-cell">¥{{ row.standardPrice.toFixed(2) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="标准时长(分钟)" min-width="180" align="center">
              <template #default="{ row }">
                <span class="duration-cell">{{ row.standardDuration }} 分钟</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="180" align="center">
              <template #default="scope">
                <div class="operation-buttons">
                  <el-button
                      type="primary"
                      size="small"
                      @click="handleEdit(scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                      type="danger"
                      size="small"
                      @click="handleDelete(scope.row)"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页组件 -->
          <div class="pagination">
            <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[5, 10, 20, 30]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="filteredServices.length"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
          </div>
        </div>

        <!-- 添加/编辑服务对话框 -->
        <el-dialog
            v-model="dialogVisible"
            :title="isEdit ? '编辑服务' : '添加服务'"
            width="500px"
        >
          <el-form
              ref="serviceFormRef"
              :model="serviceForm"
              :rules="serviceRules"
              label-width="120px"
          >
            <el-form-item label="服务类别" prop="category">
              <el-select v-model="serviceForm.category" placeholder="请选择服务类别" style="width: 100%">
                <el-option
                    v-for="category in serviceCategories"
                    :key="category"
                    :label="category"
                    :value="category"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="标准价格(元)" prop="standardPrice">
              <el-input-number
                  v-model="serviceForm.standardPrice"
                  :min="0"
                  :precision="2"
                  style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="标准时长(分钟)" prop="standardDuration">
              <el-input-number
                  v-model="serviceForm.standardDuration"
                  :min="1"
                  :step="1"
                  :precision="0"
                  style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="服务描述" prop="discription">
              <el-input
                  v-model="serviceForm.discription"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入服务描述"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="submitService">确 定</el-button>
            </span>
          </template>
        </el-dialog>
      </el-main>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import {
  HomeFilled, Menu, Setting, Bell, Monitor, CaretBottom, Refresh,
  User, Promotion, Plus
} from '@element-plus/icons-vue';
import {deleteByServiceId, getServiceList, addService, updateService} from "@/api/service/service.js";

const router = useRouter();
const username = ref('admin');
const userInitials = computed(() => {
  return username.value.charAt(0).toUpperCase();
});

// 服务类别
const serviceCategories = ref([
  '清洁服务', '照护服务', '烹饪服务', '维修服务', '其他服务'
]);

// 搜索表单
const searchForm = reactive({
  category: ''
});

// 表格加载状态
const tableLoading = ref(false);

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
});

// 所有服务数据
const allServices = ref([]);

// 过滤后的服务列表
const filteredServices = computed(() => {
  if (!allServices.value || allServices.value.length === 0) return [];

  // 应用搜索条件
  let result = [...allServices.value];

  if (searchForm.category) {
    result = result.filter(service =>
        service.category === searchForm.category
    );
  }

  return result;
});

// 当前页显示的服务
const displayedServices = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  const end = start + pagination.pageSize;
  return filteredServices.value.slice(start, end);
});

// 获取服务列表
const fetchServices = async () => {
  tableLoading.value = true;
  try {
    const response = await getServiceList();

    if (response.data && response.data.code === 200) {
      allServices.value = response.data.data;

      // 更新服务类别（去重）
      const categories = [...new Set(allServices.value.map(service => service.category))];
      serviceCategories.value = categories.length > 0 ? categories : serviceCategories.value;
    } else {
      ElMessage.error('获取服务列表失败: ' + (response.data.message || '未知错误'));
    }
  } catch (error) {
    console.error('获取服务列表失败:', error);
    ElMessage.error('获取服务列表失败，请检查网络连接');
  } finally {
    tableLoading.value = false;
  }
};

// 搜索
const searchServices = () => {
  pagination.currentPage = 1;
};

// 重置搜索
const resetSearch = () => {
  searchForm.category = '';
  pagination.currentPage = 1;
};

// 分页事件
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
};

const handleCurrentChange = (val) => {
  pagination.currentPage = val;
};

// 添加/编辑对话框相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const serviceForm = reactive({
  id: '',
  category: '',
  discription: '',
  standardPrice: 0,
  standardDuration: 60
});

// 表单规则
const serviceRules = {
  category: [{ required: true, message: '请选择服务类别', trigger: 'change' }],
  standardPrice: [{ required: true, message: '请输入标准价格', trigger: 'blur' }],
  standardDuration: [{ required: true, message: '请输入标准时长', trigger: 'blur' }],
  discription: [{ required: true, message: '请输入服务描述', trigger: 'blur' }]
};

const serviceFormRef = ref();

// 添加服务
const handleAdd = () => {
  isEdit.value = false;
  Object.assign(serviceForm, {
    id: '',
    category: '',
    discription: '',
    standardPrice: 0,
    standardDuration: 60
  });
  dialogVisible.value = true;
};

// 编辑服务
const handleEdit = (row) => {
  isEdit.value = true;
  Object.assign(serviceForm, {
    id: row.id,
    category: row.category,
    discription: row.discription,
    standardPrice: row.standardPrice,
    standardDuration: row.standardDuration
  });
  dialogVisible.value = true;
};

// 提交服务表单
const submitService = async () => {
  try {
    const serviceData = {
      id: serviceForm.id,
      category: serviceForm.category,
      discription: serviceForm.discription,
      standardPrice: serviceForm.standardPrice,
      standardDuration: serviceForm.standardDuration
    }
    if(!isEdit.value){
      const response = await addService(serviceData)
      if (response.data.code === 200){
        ElMessage.success('添加成功')
      }else{
        ElMessage.error(response.data.message || '添加失败')
      }
    }else{
      const response = await updateService(serviceData)
      if (response.data.code === 200){
        ElMessage.success('编辑成功')
      }else{
        ElMessage.error(response.data.message || '编辑失败')
      }
    }
    dialogVisible.value = false;
    await fetchServices();
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败，请稍后再试');
  }

};

// 删除服务
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该服务吗？此操作不可恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteByServiceId(row.id);

      if (response.data && response.data.code === 200) {
        ElMessage.success('服务删除成功');
        await fetchServices();
      } else {
        ElMessage.error('删除失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('删除服务失败:', error);
      ElMessage.error('删除服务失败，请稍后再试');
    }
  }).catch(() => {});
};

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command === 'logout') {
    logout();
  } else if (command === 'profile') {
    ElMessage.info('个人信息功能开发中');
  } else if (command === 'settings') {
    ElMessage.info('账号设置功能开发中');
  }
};

// 退出登录
const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    localStorage.removeItem('token');
    ElMessage({
      type: 'success',
      message: '已成功退出登录'
    });
    router.push('/login');
  }).catch(() => {});
};

// 初始化
onMounted(() => {
  fetchServices();
});
</script>

<style scoped>
/* 覆盖Element Plus的默认内边距 */
:deep(.el-header), :deep(.el-aside), :deep(.el-main) {
  padding: 0;
  margin: 0;
}

:deep(.el-main) {
  --el-main-padding: 20px;
  padding: var(--el-main-padding);
}

.home-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f5f7fa;
  position: absolute;
  left: 0;
  top: 0;
}

/* 头部样式 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0,0,0,0.08);
  z-index: 1000;
  width: 100%;
  box-sizing: border-box;
}

.header-left {
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  margin-right: 20px;
  font-weight: bold;
  font-size: 18px;
}

.logo img {
  height: 32px;
  margin-right: 8px;
}

.nav-text {
  margin-left: 15px;
}

.header-left .el-icon {
  margin-right: 15px;
  font-size: 18px;
  cursor: pointer;
}

.header-right {
  display: flex;
  align-items: center;
}

.header-right .el-icon {
  font-size: 20px;
  margin: 0 15px;
  cursor: pointer;
}

.client-btn {
  display: flex;
  align-items: center;
  margin-right: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  margin-left: 20px;
  cursor: pointer;
}

.user-info span {
  margin: 0 8px;
}

/* 主容器样式 */
.main-container {
  display: flex;
  flex: 1;
  overflow: hidden;
  width: 100%;
  margin: 0;
  padding: 0;
}

/* 侧边栏样式 */
.sidebar {
  background-color: #fff;
  height: 100%;
  box-shadow: 1px 0 4px rgba(0,0,0,0.08);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20px;
  z-index: 900;
  width: 64px !important;
  min-width: 64px;
  flex-shrink: 0;
  margin: 0;
  padding-left: 0;
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 64px;
  cursor: pointer;
  color: #606266;
  transition: all 0.3s;
}

.menu-item span {
  font-size: 12px;
  margin-top: 5px;
}

.menu-item .el-icon {
  font-size: 20px;
}

.menu-item.active {
  color: #1989fa;
  background-color: #f0f7ff;
}

.menu-item:hover {
  background-color: #f5f7fa;
}

/* 主内容区域样式 */
.main-content {
  flex: 1;
  overflow-y: auto;
  width: calc(100% - 64px);
  box-sizing: border-box;
}

/* 分页样式 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 搜索栏样式 */
.search-bar {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.05);
}

/* 新增样式 */
.price-cell {
  font-weight: 500;
  color: #e6a23c;
}

.duration-cell {
  font-weight: 500;
  color: #409eff;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}
</style>